package com.cn.kehong.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.api.*;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.*;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@EnableScheduling
@Service
public class ProductPeiTouServiceImpl implements IProductPeiTouService {

    @Autowired
    private ProductPeiTouMapper productPeiTouMapper;

    @Autowired
    private ISysItemService sysItemService;

    @Autowired
    private ISysSupplierService sysSupplierService;

    @Autowired
    private IProductPeiJobSupplierService productPeiJobSupplierService;

    //粗磨
    @Autowired
    private IProductThinPeriodService productThinPeriodService;

    //细磨
    @Autowired
    private IProductThickPeriodService productThickPeriodService;

    //除磁
    @Autowired
    private IProductChuciPeriodService productChuciPeriodService;

    //干燥
    @Autowired
    private IProductGzPeriodService productGzPeriodService;

    //烧结
    @Autowired
    private IProductSaojiePeriodService productSaojiePeriodService;

    @Autowired
    private IProductSaojieGuanService productSaojieGuanService;

    @Autowired
    private IProductPackageService productPackageService;

    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private XunjianTaskMapper xunjianTaskMapper;

    @Autowired
    private ProductThinPeriodMapper productThinPeriodMapper;
    @Autowired
    private ProductThickPeriodMapper productThickPeriodMapper;

    @Autowired
    private ProductChuciPeriodMapper productChuciPeriodMapper;

    @Autowired
    private ProductGzPeriodMapper productGzPeriodMapper;
    @Autowired
    private ProductSaojieJobMapper productSaojieJobMapper;
    @Autowired
    private ProductDianciPeriodMapper productDianciPeriodMapper;
    @Autowired
    private ProductPackageMapper productPackageMapper;
    @Autowired
    private ProductPackageJobMapper productPackageJobMapper;
    @Autowired
    private ProductDianciFenjiRecordMapper productDianciFenjiRecordMapper;
    @Autowired
    private SysItemMapper sysItemMapper;
    @Autowired
    private Config config;

    @Override
    public List<ProductPeiTou> getProductPeiTouList(QueryForm queryForm) throws Exception {
        int count = productPeiTouMapper.selectProductPeiTouCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectProductPeiTous(queryForm);
        productPeiTous.get(0).setCount(count);

        return productPeiTous;
    }

    @Override
    public List<ProductPeiTou> getProductPeiTouDutyDayList(QueryForm queryForm) throws Exception {
        Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        ProductPeiTouExample example = new ProductPeiTouExample();
        ProductPeiTouExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(Constants.NORMAL_STATUS);
        if (StringUtils.isNotEmpty(queryForm.getFactoryName())) {
            criteria.andFactoryNameEqualTo(queryForm.getFactoryName());
        }
        if (StringUtils.isNotEmpty(queryForm.getPeiStatus())) {
            criteria.andPeiStatusEqualTo(queryForm.getPeiStatus());
        }
        if (StringUtils.isNotEmpty(queryForm.getPeiNotStatus())) {
            criteria.andPeiStatusNotEqualTo(queryForm.getPeiNotStatus());
        }
        if (StringUtils.isNotEmpty(queryForm.getTouStatus())) {
            criteria.andTouStatusEqualTo(queryForm.getTouStatus());
        }
        if (StringUtils.isNotEmpty(queryForm.getTouNotStatus())) {
            criteria.andTouStatusNotEqualTo(queryForm.getTouNotStatus());
        }
        if (StringUtils.isNotEmpty(queryForm.getJzNotStatus())) {
            criteria.andJiWeightStatusNotEqualTo(queryForm.getJzNotStatus());
        }
//        criteria.andWhiteDutyEqualTo(dutyMap.get("whiteDay"));
//        criteria.andDutyDayEqualTo(dutyMap.get("dutyDay"));
        example.setOrderByClause("create_time desc");
        List<ProductPeiTou> list = productPeiTouMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<ProductPeiTou> getProductUnCompleteOrDutyPeiTous(QueryForm queryForm) throws Exception {
        Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        queryForm.setDutyDay(dutyMap.get("dutyDay"));
        queryForm.setWhiteDuty(dutyMap.get("whiteDay"));
        List<ProductPeiTou> list = productPeiTouMapper.selectProductUnCompleteOrDutyPeiTous(queryForm);
        return list;
    }


    @Override
    public Map<String, Integer> getProductPeiTouDutyDayCountMap(QueryForm queryForm) throws Exception {
        List<ProductPeiTou> list = this.getProductPeiTouDutyDayList(queryForm);
        Map<String, Integer> mapResult = Maps.newHashMap();
        mapResult.put("undo", 0);
        mapResult.put("doing", 0);
        for (ProductPeiTou productPeiTou : list) {
            if (StringUtils.equals(productPeiTou.getPeiStatus(), "0")) {
                int count = mapResult.get("undo");
                mapResult.put("undo", count + 1);
            } else if (StringUtils.equals(productPeiTou.getPeiStatus(), "1")) {
                int count = mapResult.get("doing");
                mapResult.put("doing", count + 1);
            }
        }
        return mapResult;
    }

    @Override
    public Map<String, Object> getScanQRCode(String qrCode) throws Exception {
        Map<String, Object> map = Maps.newHashMap();
        map.put("errorMsg", "");
        if (StringUtils.isEmpty(qrCode)) {
            map.put("errorMsg", "二维码参数为空");
            return map;
        }
        if (qrCode.length() != 30) {
            map.put("errorMsg", "二维码长度不正确：" + qrCode.length());
            return map;
        }
        String materialCode = qrCode.substring(0, 10);
        String supplierCode = qrCode.substring(10, 16);
        String productTime = qrCode.substring(16, 22);
        String productCode = qrCode.substring(22, 30);

        List<SysItem> sysItems = sysItemService.getMgItemByType("8");
        Map<String, SysItem> sysItemMap = Maps.newHashMap();
        for (SysItem sysItem : sysItems) {
            sysItemMap.put(sysItem.getItemCode(), sysItem);
        }
        if (!sysItemMap.containsKey(materialCode)) {
            map.put("errorMsg", "未查询到物料编码：" + materialCode);
            return map;
        }

        Map<String, SysSupplier> sysSupplierMap = sysSupplierService.getSysSupplierByCode();
        if (!sysSupplierMap.containsKey(supplierCode)) {
            map.put("errorMsg", "未查询到供应商代码：" + supplierCode);
            return map;
        }
        SysItem sysItem = sysItemMap.get(materialCode);
        ProductPeiJobSupplier productPeiJobSupplier = new ProductPeiJobSupplier();
        String peiType = StringUtils.equals(sysItem.getItemName(), "辅料") ? "2" : "1";
        productPeiJobSupplier.setPeiType(peiType);
        productPeiJobSupplier.setMaterialId(sysItem.getId());
        productPeiJobSupplier.setMaterialCode(materialCode);
        productPeiJobSupplier.setMaterialName(sysItem.getItemAlias());
        productPeiJobSupplier.setProductCode(productCode);
        productPeiJobSupplier.setPeiNum("0");
        productPeiJobSupplier.setPeiWeight("0");
        productPeiJobSupplier.setMaterialType(sysItem.getItemPrice());

        SysSupplier sysSupplier = sysSupplierMap.get(supplierCode);
        productPeiJobSupplier.setSupplierId(sysSupplier.getId());
        productPeiJobSupplier.setSupplierName(sysSupplier.getSupplierName());
        productPeiJobSupplier.setSupplierCode(sysSupplier.getSupplierCode());
        productPeiJobSupplier.setProductTime(productTime);
        map.put("job", productPeiJobSupplier);
        return map;
    }

    @Override
    public String getProductPeiTouCount() throws Exception {
        ProductPeiTouExample example = new ProductPeiTouExample();
        ProductPeiTouExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(Constants.NORMAL_STATUS);
        int count = productPeiTouMapper.countByExample(example) + 1;
        String existCount = generateUUID.getFourNumStr(count);
        return existCount;
    }

    @Override
    public String addProductPeiTou(ProductPeiTou productPeiTou) throws Exception {
        String boxCode = productPeiTou.getBoxCode();
        String factoryName = productPeiTou.getFactoryName();
        if (StringUtils.isEmpty(boxCode) || StringUtils.isEmpty(factoryName)) {
            return "参数异常！";
        }
        String productCode = productPeiTou.getProductCode();
        if (productPeiTouMapper.selectProductPeiTouByCode(productCode) > 0) {
            return "起批号已经存在";
        }
        Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andBoxCodeEqualTo(boxCode).andFactoryNameEqualTo(factoryName)
                .andTouStatusNotEqualTo("2")
                .andStatusEqualTo(Constants.NORMAL_STATUS);
//        int existCount = productPeiTouMapper.countByExample(example);
//        if (existCount > 0) {
//            return "上一批次投料完成方可起批";
//        }

        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yy");
        String year = simpleDateFormat1.format(new Date());
        String startCode = factoryName.split("-")[0] + year + productCode;
        productPeiTou.setStartCode(startCode);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String qpTime = simpleDateFormat.format(new Date());
        productPeiTou.setQiStartTime(qpTime);
        productPeiTou.setWhiteDuty(whiteDay);
        productPeiTou.setDutyDay(dutyDay);
        String id = CommonUtil.generateRandomNum("peitou-");
        productPeiTou.setId(id);
        int count = productPeiTouMapper.insertSelective(productPeiTou);
        if (count>0){
            XunjianTask xunjianTask = new XunjianTask();
            xunjianTask.setId(CommonUtil.generateRandomNum("xjtask-"));
            xunjianTask.setFactoryName(productPeiTou.getFactoryName());
            xunjianTask.setLineType("1");
            xunjianTask.setWorkProcess("混料");
            xunjianTask.setTaskName("投料巡检");
            xunjianTask.setFrequency("1次/批");
            xunjianTask.setProductCode(productPeiTou.getStartCode()+"-"+productPeiTou.getGradeValue());
            xunjianTask.setCreateTime(new Date());
            String banCi = productPeiTou.getWhiteDuty();
            xunjianTask.setBanCi(StringUtils.equals(banCi, "1") ? "A" : "B");
            count = xunjianTaskMapper.insertSelective(xunjianTask);
            if(count < 1){
                throw new Exception("插入巡检表异常！");
            }
        }
        String resp = productThinPeriodService.addProductThinPeriod(id, productPeiTou.getProductCode(), factoryName, startCode);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception("添加粗磨数据异常！");
        }
        resp = productThickPeriodService.addProductThickPeriod(id, productPeiTou.getProductCode(), factoryName, startCode);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception("添加细磨数据异常！");
        }
        resp = productChuciPeriodService.addProductChuciPeriod(id, productPeiTou.getProductCode(), factoryName, startCode);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception("添加除磁数据异常！");
        }
        resp = productGzPeriodService.addProductGzPeriod(id, productPeiTou.getProductCode(), factoryName, startCode);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception("添加干燥数据异常！");
        }
        resp = productSaojiePeriodService.addProductSaojiePeriod(id, productPeiTou.getProductCode(), factoryName, startCode);
        if (StringUtils.isNotEmpty(resp)) {
            throw new Exception("添加烧结数据异常！");
        }
//        resp = productDianciPeriodService.addProductDianciPeriod(id, productPeiTou.getProductCode(), factoryName);
//        if (StringUtils.isNotEmpty(resp)) {
//            throw new Exception("添加电除磁数据异常！");
//        }

        return CommonUtil.outStr(count);
    }

    @Override
    public String updateProductPeiTou(ProductPeiTou productPeiTou) throws Exception {
        String id = productPeiTou.getId();
        if (StringUtils.isEmpty(id)) {
            return "主键id不能为空！";
        }
        String touStatus = productPeiTou.getTouStatus();
        ProductPeiTou exist = productPeiTouMapper.selectProductPeiTouById(id);
        if (null == exist) {
            return "配料信息不存在";
        }
        if (StringUtils.isNotEmpty(touStatus)) {
            if (StringUtils.equals(exist.getPeiStatus(), "0")) {
                return "未进行配料，无法投料！";
            }
        }
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andIdEqualTo(id);
        int count = productPeiTouMapper.updateByExampleSelective(productPeiTou, example);
        if (count > 0) {
            XunjianTask xunjianTask = new XunjianTask();
            xunjianTask.setAttr16(id);
            xunjianTask.setFactoryName(exist.getFactoryName());
            xunjianTask.setLineType("1");
            xunjianTask.setWorkPeriod("混料");
            xunjianTask.setProductCode(exist.getStartCode());
            String banCi = StringUtils.equals(exist.getDutyDay(), "1") ? "A" : "B";
            xunjianTask.setBanCi(banCi);
            xunjianTask.setTaskName("混料工序");
            xunjianTask.setFrequency("1次/批");
            xunjianTask.setId(CommonUtil.generateRandomNum("xjtask-"));
            count = xunjianTaskMapper.insertSelective(xunjianTask);
            if (count < 1) {
                throw new Exception("插入巡检表异常！");
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateEndProductPeiTouByCodes(List<String> productCodes) throws Exception {
        if (CollectionsUtil.isEmpty(productCodes)) {
            return "";
        }
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andProductCodeIn(productCodes);
        ProductPeiTou update = new ProductPeiTou();
        update.setFinalStatus("1");
        int count = productPeiTouMapper.updateByExampleSelective(update, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String deleteProductPeiTou(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            return "主键id不能为空！";
        }
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andIdEqualTo(id);
        ProductPeiTou update = new ProductPeiTou();
        update.setStatus(Constants.DEL_STATUS);
        int count = productPeiTouMapper.updateByExampleSelective(update, example);
        if (count>0){
            ProductPeiTouExample example1 = new ProductPeiTouExample();
            example.createCriteria().andIdEqualTo(id);
            List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(example1);
            String productCode=productPeiTous.get(0).getProductCode()+"-"+productPeiTous.get(0).getGradeValue();
            XunjianTaskExample taskExample = new XunjianTaskExample();
            taskExample.createCriteria().andProductCodeEqualTo(productCode);
            List<XunjianTask> xunjianTasks = xunjianTaskMapper.selectByExample(taskExample);
            if (xunjianTasks.size()>0){
                for (XunjianTask xunjianTask :xunjianTasks){
                    //状态设置为已取消
                    xunjianTask.setXjStatus("4");
                    xunjianTaskMapper.updateByExampleSelective(xunjianTask,taskExample);
                }
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String addAPIProductPeiJobs(ProductPeiTou productPeiTou) throws Exception {
        List<ProductPeiJobSupplier> productPeiJobSuppliers = productPeiTou.getProductPeiJobSuppliers();
        if (CollectionUtils.isEmpty(productPeiJobSuppliers)) {
            return "数组为空";
        }
        String peiId = productPeiTou.getId();
        if (StringUtils.isEmpty(peiId)) {
            return "id不能为空";
        }
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andIdEqualTo(peiId).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(productPeiTous)) {
            return "配料不存在";
        }
        ProductPeiTou exist = productPeiTous.get(0);
        if (StringUtils.equals(exist.getPeiStatus(), "2")) {
            return "配料已经结束";
        }
        for (ProductPeiJobSupplier supplier : productPeiJobSuppliers) {
            supplier.setPeiId(peiId);
        }
        String resp = productPeiJobSupplierService.addBatchProductPeiJobSuppliers(productPeiJobSuppliers);
        if (StringUtils.isNotEmpty(resp)) {
            return resp;
        }
        ProductPeiTou update = new ProductPeiTou();
        update.setPeiStatus(productPeiTou.getPeiStatus());
        update.setPeiStartTime(productPeiTou.getPeiStartTime());
        update.setPeiUserName(productPeiTou.getPeiUserName());
        if (StringUtils.equals(productPeiTou.getPeiStatus(), "2")) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String peiEndTime = simpleDateFormat.format(new Date());
            update.setPeiEndTime(peiEndTime);
            Date startTime = simpleDateFormat.parse(productPeiTou.getPeiStartTime());
            long second = (new Date().getTime() - startTime.getTime()) / 1000;
            String min = NumberUtil.getPoint(second / 60.0, 1);
            update.setPeiSpendTime(min);
        }
        int count = productPeiTouMapper.updateByExampleSelective(update, example);
        if (count < 1) {
            throw new Exception("更新表异常！");
        }
        return "";
    }

    @Override
    public List<ProductPeiJobSupplier> getProductPeiJobSuppliersByPeiId(String peiId) throws Exception {
        return productPeiJobSupplierService.getProductPeiJobSupplierByPeiId(peiId);
    }

    @Override
    public List<ProductPeiTou> getProductPeiTouBackList(QueryForm queryForm) throws Exception {
        int count = productPeiTouMapper.getProductPeiTouBackCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProductPeiTouBackList(queryForm);
        productPeiTous.get(0).setCount(count);
        return productPeiTous;
    }

    public Map<String, Object> getProductionCount() throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        QueryForm queryForm = new QueryForm();
        QueryForm queryForm1 = new QueryForm();
        queryForm.setPeiStatus("2");
        int qpCount = productPeiTouMapper.selectProductPeiTouCount(queryForm); // 起批配料
        resultMap.put("qpCount", qpCount);

        queryForm1.setTouNotStatus("2");
        int tlCount = productPeiTouMapper.selectProductPeiTouCount(queryForm1); // 投料混料
        resultMap.put("tlCount", tlCount);

        queryForm.setStatus("1");
        int cmCount = productThinPeriodMapper.selectProductThinPeriodCount(queryForm); // 粗磨
        resultMap.put("cmCount", cmCount);

        queryForm.setStatus("1");
        int xmCount = productThickPeriodMapper.selectProductThickPeriodCount(queryForm); // 细磨
        resultMap.put("xmCount", xmCount);

        queryForm.setStatus("1");
        int ccCount = productChuciPeriodMapper.selectProductChuCiCount(queryForm); // 除磁
        resultMap.put("ccCount", ccCount);

        queryForm.setStatus("1");
        int gzCount = productGzPeriodMapper.selectProductProductGzPeriodCount(queryForm); // 干燥
        resultMap.put("gzCount", gzCount);

        queryForm.setStatus("1");
        int sjCount = productSaojieJobMapper.selectProductSaojieJobCount(queryForm); // 烧结
        resultMap.put("sjCount", sjCount);

        queryForm.setStatus("1");
        int fjCount = productDianciPeriodMapper.selectProductDianciPeriodsCount(queryForm); // 电除磁 分级
        resultMap.put("fjCount", fjCount);

        queryForm.setStatus("0");
        int bzCount = productPackageMapper.selectProductPackagePeriodCount(queryForm); // 包装
        resultMap.put("bzCount", bzCount);

        return resultMap;
    }

    @Override
    public Map<String, Object> getProductBackCount() throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        QueryForm queryForm = new QueryForm();
        int qpCount = productPeiTouMapper.getProductPeiTouBackCount(queryForm); // 起批配料
        resultMap.put("qpCount", qpCount);

        queryForm.setTouNotStatus("0");
        int tlCount = productPeiTouMapper.getProductPeiTouBackCount(queryForm); // 投料混料
        resultMap.put("tlCount", tlCount);

        queryForm.setStatus("2");
        int cmCount = productThinPeriodMapper.getProductThinPeriodBackCount(queryForm); // 粗磨
        resultMap.put("cmCount", cmCount);

        queryForm.setStatus("2");
        int xmCount = productThickPeriodMapper.getProductThickPeriodBackCount(queryForm); // 细磨
        resultMap.put("xmCount", xmCount);

        queryForm.setStatus("2");
        int ccCount = productChuciPeriodMapper.selectProductChuCiCount(queryForm); // 除磁
        resultMap.put("ccCount", ccCount);

        queryForm.setStatus("2");
        int gzCount = productGzPeriodMapper.getProductGzPeriodBackCount(queryForm); // 干燥
        resultMap.put("gzCount", gzCount);

        queryForm.setStatus("2");
        int sjCount = productSaojieJobMapper.getProductSaojieJobBackCount(queryForm); // 烧结
        resultMap.put("sjCount", sjCount);

        queryForm.setStatus("2");
        int fjCount = productDianciPeriodMapper.getProductDianciPeriodBackCount(queryForm); // 电除磁 分级
        resultMap.put("fjCount", fjCount);

        queryForm.setStatus("1");
        int bzCount = productPackageMapper.selectProductPackagePeriodCount(queryForm); // 包装
        resultMap.put("bzCount", bzCount);

        return resultMap;
    }

    @Override
    public Map<String, Object> getProductPeiTouDutyDayCount(QueryForm queryForm) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        //带配料
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPeiStatusEqualTo("0").andFactoryNameEqualTo(queryForm.getFactoryName());
        int dplCount = productPeiTouMapper.countByExample(example);
        //配料中
        ProductPeiTouExample example1 = new ProductPeiTouExample();
        example1.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPeiStatusEqualTo("1").andFactoryNameEqualTo(queryForm.getFactoryName());
        int plzCount = productPeiTouMapper.countByExample(example1);
        resultMap.put("dplCount", dplCount);
        resultMap.put("plzCount", plzCount);
        return resultMap;
    }

    @Override
    public List<ProductPeiTou> getProduceByDay(QueryForm queryForm) throws Exception {
        //如果没有传时间
        if (StringUtils.isEmpty(queryForm.getStartTime())&& StringUtils.isEmpty(queryForm.getBanCi())) {
            //判断当前时间属于白班还是夜班
            // 获取当前时间
//            setShiftTimes(queryForm, now);
            Map<String, String> duty = CommonUtil.getOnDutyAndWhiteDay();
            queryForm.setBanCi(duty.get("whiteDay"));
            queryForm.setDutyDay(duty.get("dutyDay"));
        }
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProduceByDay(queryForm);
        for (ProductPeiTou peiTou : productPeiTous) {
            SysItemExample example = new SysItemExample();
            example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andItemTypeEqualTo("9").andItemTitleEqualTo(peiTou.getGradeValue());
            List<SysItem> sysItems = sysItemMapper.selectByExample(example);
            //获取当前规格下的理论产量
            String itemAttr = sysItems.get(0).getItemAttr();
            int counts = peiTou.getCounts();
            BigDecimal itemAttrBigDecimal = new BigDecimal(itemAttr);
            BigDecimal countsBigDecimal = BigDecimal.valueOf(counts);
            BigDecimal result = itemAttrBigDecimal.multiply(countsBigDecimal);
            //理论产出
            String llOutput = result.setScale(1, RoundingMode.HALF_UP).toString();
            peiTou.setLlOutput(llOutput);
            String sjOutput = printSampleInfo(peiTou.getFactoryName(), peiTou.getGradeValue(), peiTou.getWhiteDuty(), queryForm);
            peiTou.setSjOutput(sjOutput);
        }
        return productPeiTous;

    }

    @Override
    public List<ProductPeiTou> getProduceByBanCi(QueryForm queryForm) throws Exception {
        // 如果没有传时间，查询单日投入产出
        if (StringUtils.isEmpty(queryForm.getStartTime())) {
            // 获取今天的时间
            LocalDateTime startDateTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            LocalDateTime endDateTime = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startTime = startDateTime.format(formatter);
            String endTime = endDateTime.format(formatter);
            queryForm.setStartTime(startTime);
            queryForm.setEndTime(endTime);
        }

        List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProduceByDay(queryForm);

        Map<String, ProductPeiTou> groupedByFactoryName = new HashMap<>();

        for (ProductPeiTou peiTou : productPeiTous) {
            // 获取当前规格下的理论产量
            SysItemExample example = new SysItemExample();
            example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andItemTypeEqualTo("9").andItemTitleEqualTo(peiTou.getGradeValue());
            List<SysItem> sysItems = sysItemMapper.selectByExample(example);
            String itemAttr = sysItems.get(0).getItemAttr();
            int counts = peiTou.getCounts();
            BigDecimal itemAttrBigDecimal = new BigDecimal(itemAttr);
            BigDecimal countsBigDecimal = BigDecimal.valueOf(counts);
            BigDecimal result = itemAttrBigDecimal.multiply(countsBigDecimal);
            String llOutput = result.setScale(1, RoundingMode.HALF_UP).toString();
            String sjOutput = printSampleInfo1(peiTou.getFactoryName(), peiTou.getGradeValue(), queryForm);

            // 如果该车间已经存在，则进行累加
            if (groupedByFactoryName.containsKey(peiTou.getFactoryName())) {
                ProductPeiTou existingPeiTou = groupedByFactoryName.get(peiTou.getFactoryName());
                // 累加 counts
                existingPeiTou.setCounts(existingPeiTou.getCounts() + counts);
                // 累加 llOutput (理论产量)，需要转成 BigDecimal 来累加
                BigDecimal existingLlOutput = new BigDecimal(existingPeiTou.getLlOutput());
                BigDecimal newLlOutput = new BigDecimal(llOutput);
                existingPeiTou.setLlOutput(existingLlOutput.add(newLlOutput).setScale(1, RoundingMode.HALF_UP).toString());
                // 累加 sjOutput
                BigDecimal existingSjOutput = new BigDecimal(existingPeiTou.getSjOutput());
                BigDecimal newSjOutput = new BigDecimal(sjOutput);
                existingPeiTou.setSjOutput(existingSjOutput.add(newSjOutput).setScale(1, RoundingMode.HALF_UP).toString());
            } else {
                // 如果是第一次遇到该车间，保存
                peiTou.setLlOutput(llOutput);
                peiTou.setSjOutput(sjOutput);
                groupedByFactoryName.put(peiTou.getFactoryName(), peiTou);
            }
        }

        return new ArrayList<>(groupedByFactoryName.values());
    }

    @Override
    public void exportProduceByDay(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String, Object> results = Maps.newHashMap();
        //如果没有传时间
        if (StringUtils.isEmpty(queryForm.getStartTime())) {
            //判断当前时间属于白班还是夜班
            // 获取当前时间
//            LocalDateTime now = LocalDateTime.now();
            Map<String, String> duty = CommonUtil.getOnDutyAndWhiteDay();
            queryForm.setBanCi(duty.get("whiteDay"));
            queryForm.setDutyDay(duty.get("dutyDay"));
        }
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProduceByDay(queryForm);
        for (ProductPeiTou peiTou : productPeiTous) {
            SysItemExample example = new SysItemExample();
            example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andItemTypeEqualTo("9").andItemTitleEqualTo(peiTou.getGradeValue());
            List<SysItem> sysItems = sysItemMapper.selectByExample(example);
            //获取当前规格下的理论产量
            String itemAttr = sysItems.get(0).getItemAttr();
            int counts = peiTou.getCounts();
            BigDecimal itemAttrBigDecimal = new BigDecimal(itemAttr);
            BigDecimal countsBigDecimal = BigDecimal.valueOf(counts);
            BigDecimal result = itemAttrBigDecimal.multiply(countsBigDecimal);
            //理论产出
            String llOutput = result.setScale(1, RoundingMode.HALF_UP).toString();
            peiTou.setLlOutput(llOutput);
            String sjOutput = printSampleInfo(peiTou.getFactoryName(), peiTou.getGradeValue(), peiTou.getWhiteDuty(), queryForm);
            peiTou.setSjOutput(sjOutput);
        }
        results.put("list", productPeiTous);
        String fileName = CommonUtil.generateRandomNum("db-") + ".xlsx";
        String filePath = config.filePath + fileName;
        String formattedStartTime = queryForm.getStartTime().substring(0, 10);
        String formattedEndTime = queryForm.getEndTime().substring(0, 10);
        String nameStr = "投入产出单班统计" + formattedStartTime + "-" + formattedEndTime + ".xlsx";
        TemplateExcelUtils.downLoadExcel(filePath, nameStr, results, "dbtj.xlsx", response);
    }

    @Override
    public void exportProduceByBanCi(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String, Object> results = Maps.newHashMap();
        // 如果没有传时间，查询单日投入产出
        if (StringUtils.isEmpty(queryForm.getStartTime())) {
            // 获取今天的时间
            LocalDateTime startDateTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            LocalDateTime endDateTime = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startTime = startDateTime.format(formatter);
            String endTime = endDateTime.format(formatter);
            queryForm.setStartTime(startTime);
            queryForm.setEndTime(endTime);
        }

        List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProduceByDay(queryForm);

        Map<String, ProductPeiTou> groupedByFactoryName = new HashMap<>();

        for (ProductPeiTou peiTou : productPeiTous) {
            // 获取当前规格下的理论产量
            SysItemExample example = new SysItemExample();
            example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andItemTypeEqualTo("9").andItemTitleEqualTo(peiTou.getGradeValue());
            List<SysItem> sysItems = sysItemMapper.selectByExample(example);
            String itemAttr = sysItems.get(0).getItemAttr();
            int counts = peiTou.getCounts();
            BigDecimal itemAttrBigDecimal = new BigDecimal(itemAttr);
            BigDecimal countsBigDecimal = BigDecimal.valueOf(counts);
            BigDecimal result = itemAttrBigDecimal.multiply(countsBigDecimal);
            String llOutput = result.setScale(1, RoundingMode.HALF_UP).toString();
            String sjOutput = printSampleInfo1(peiTou.getFactoryName(), peiTou.getGradeValue(), queryForm);

            // 如果该车间已经存在，则进行累加
            if (groupedByFactoryName.containsKey(peiTou.getFactoryName())) {
                ProductPeiTou existingPeiTou = groupedByFactoryName.get(peiTou.getFactoryName());
                // 累加 counts
                existingPeiTou.setCounts(existingPeiTou.getCounts() + counts);
                // 累加 llOutput (理论产量)，需要转成 BigDecimal 来累加
                BigDecimal existingLlOutput = new BigDecimal(existingPeiTou.getLlOutput());
                BigDecimal newLlOutput = new BigDecimal(llOutput);
                existingPeiTou.setLlOutput(existingLlOutput.add(newLlOutput).setScale(1, RoundingMode.HALF_UP).toString());
                // 累加 sjOutput
                BigDecimal existingSjOutput = new BigDecimal(existingPeiTou.getSjOutput());
                BigDecimal newSjOutput = new BigDecimal(sjOutput);
                existingPeiTou.setSjOutput(existingSjOutput.add(newSjOutput).setScale(1, RoundingMode.HALF_UP).toString());
            } else {
                // 如果是第一次遇到该车间，直接保存
                peiTou.setLlOutput(llOutput);
                peiTou.setSjOutput(sjOutput);
                groupedByFactoryName.put(peiTou.getFactoryName(), peiTou);
            }
        }
        results.put("list", groupedByFactoryName.values());
        String fileName = CommonUtil.generateRandomNum("dr-") + ".xlsx";
        String filePath = config.filePath + fileName;
        String formattedStartTime = queryForm.getStartTime().substring(0, 10);
        String formattedEndTime = queryForm.getEndTime().substring(0, 10);
        String nameStr = "投入产出单日统计" + formattedStartTime + "-" + formattedEndTime + ".xlsx";
        TemplateExcelUtils.downLoadExcel(filePath, nameStr, results, "drtj.xlsx", response);
    }

    @Override
    public List<JSONObject> getProductPeiTouToday() throws Exception {
        Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andDutyDayEqualTo(dutyDay);
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(example);
        List<JSONObject> jsonObjects = Lists.newLinkedList();
//        JSONObject header = new JSONObject();
//        header.put("first","");
//        header.put("second","16-1");
//        header.put("third","16-2");
//        header.put("four","合计");
//        jsonObjects.add(header);
        int A161 = 0;
        int A162 = 0;
        int B161 = 0;
        int B162 = 0;
        for(ProductPeiTou peiTou:productPeiTous){
            String factory = peiTou.getFactoryName();
            String whiteDay = peiTou.getWhiteDuty();
            if(StringUtils.equals(factory,"16-1")){
                if(StringUtils.equals(whiteDay,"1")){
                    ++A161;
                }else{
                    ++B161;
                }
            }else if(StringUtils.equals(factory,"16-2")){
                if(StringUtils.equals(whiteDay,"1")){
                    ++A162;
                }else{
                    ++B162;
                }
            }
        }
        JSONObject data1 = new JSONObject();
        data1.put("first","A班");
        data1.put("second",A161);
        data1.put("third",A162);
        data1.put("four",A161+A162);
        jsonObjects.add(data1);

        JSONObject data2 = new JSONObject();
        data2.put("first","B班");
        data2.put("second",B161);
        data2.put("third",B162);
        data2.put("four",B161+B162);
        jsonObjects.add(data2);

        JSONObject data3 = new JSONObject();
        data3.put("first","合计");
        data3.put("second",A161+B161);
        data3.put("third",A162+B162);
        data3.put("four",A161+B161+A162+B162);
        jsonObjects.add(data3);
        return jsonObjects;
    }

    @Override
    public void exportDateBack(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String, Object> result = Maps.newHashMap();
        //起批配料
        if (queryForm.getType().equals("0")){
//            List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProductPeiTouBackList(queryForm);
            List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProductPeiTouBackListEx(queryForm);
            result.put("list", productPeiTous);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-起批配料.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process.xlsx", response);
        }else if (queryForm.getType().equals("1")){
//            List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProductPeiTouBackList(queryForm);
            List<ProductPeiTou> productPeiTous = productPeiTouMapper.getProductPeiTouBackListEx(queryForm);
            result.put("list", productPeiTous);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-投料混料.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process0.xlsx", response);
        }else if (queryForm.getType().equals("2")){
//            List<ProductThinPeriod> productThinPeriods = productThinPeriodMapper.getProductThinPeriodBackList(queryForm);
            List<ProductThinPeriod> productThinPeriods = productThinPeriodMapper.getProductThinPeriodBackListEx(queryForm);
            result.put("list", productThinPeriods);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-粗磨.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process1.xlsx", response);
        }else if (queryForm.getType().equals("3")){
//            List<ProductThickPeriod> productThickPeriods = productThickPeriodMapper.getProductThickPeriodBackList(queryForm);
            List<ProductThickPeriod> productThickPeriods = productThickPeriodMapper.getProductThickPeriodBackListEx(queryForm);
            result.put("list", productThickPeriods);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-细磨.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process2.xlsx", response);
        }else if (queryForm.getType().equals("4")){
//            List<ProductChuciPeriod> productThinPeriods = productChuciPeriodMapper.getProductChuciPeriodBackList(queryForm);
            List<ProductChuciPeriod> productThinPeriods = productChuciPeriodMapper.getProductChuciPeriodBackListEx(queryForm);
            result.put("list", productThinPeriods);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-除磁.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process3.xlsx", response);
        }else if (queryForm.getType().equals("5")){
//            List<ProductGzPeriod> productGzPeriods = productGzPeriodMapper.getProductGzPeriodBackList(queryForm);
            List<ProductGzPeriod> productGzPeriods = productGzPeriodMapper.getProductGzPeriodBackListEx(queryForm);
            result.put("list", productGzPeriods);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-干燥.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process4.xlsx", response);
        }else if (queryForm.getType().equals("6")){
//            List<ProductSaojieJob> productSaojieJobs = productSaojieJobMapper.getProductSaojieJobBackList(queryForm);
            List<ProductSaojieJob> productSaojieJobs = productSaojieJobMapper.getProductSaojieJobBackListEx(queryForm);
            result.put("list", productSaojieJobs);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-烧结.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process5.xlsx", response);
        }else if (queryForm.getType().equals("7")){
//            List<ProductDianciPeriod> productDianciPeriods = productDianciPeriodMapper.getProductDianciPeriodBackList(queryForm);
            List<ProductDianciPeriod> productDianciPeriods = productDianciPeriodMapper.getProductDianciPeriodBackListEx(queryForm);
            for (ProductDianciPeriod productDianciPeriod :productDianciPeriods){
                if (StringUtils.isNotBlank(productDianciPeriod.getDianciEndTime())){
                    productDianciPeriod.setDianciStatus("已完成");
                }else if (StringUtils.isNotBlank(productDianciPeriod.getDianciStartTime())){
                    productDianciPeriod.setDianciStatus("除磁中");
                }
                if (StringUtils.isNotBlank(productDianciPeriod.getFenjiEndTime())){
                    productDianciPeriod.setFenjiStatus("已完成");
                }else if (StringUtils.isNotBlank(productDianciPeriod.getFenjiStartTime())){
                    productDianciPeriod.setFenjiStatus("分级中");
                }
            }
            result.put("list", productDianciPeriods);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-电除磁/分级.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process6.xlsx", response);
        }else if (queryForm.getType().equals("9")){
//            List<ProductPackage> productPackages = productPackageMapper.selectProductPackagePeriods(queryForm);
            List<ProductPackage> productPackages = productPackageMapper.selectProductPackagePeriodsEx(queryForm);
            result.put("list", productPackages);
            String fileName = CommonUtil.generateRandomNum("制程追溯-") + ".xlsx";
            String filePath = config.filePath + fileName;
            String nameStr = "制程追溯-包装.xlsx";
            TemplateExcelUtils.downLoadExcel(filePath, nameStr, result, "process7.xlsx", response);
        }


    }

    @Override
    public List<ProductPeiTou> getGradeByCode(ProductPeiTou productPeiTou) throws Exception {
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andStartCodeEqualTo(productPeiTou.getStartCode());
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(example);
        return productPeiTous;
    }

    @Override
    public List<ProductPeiTou> getProductPeiTouList1(QueryForm queryForm) throws Exception {
        int count = productPeiTouMapper.selectProductPeiTouCount1(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectProductPeiTous1(queryForm);
        productPeiTous.get(0).setCount(count);

        return productPeiTous;
    }

    @Override
    public String printSampleInfo(String factoryName, String gradeValue, String banCi, QueryForm queryForm) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        setShiftTimes(queryForm, now);
        ProductPackageExample packageExample = new ProductPackageExample();
        packageExample.createCriteria().andFactoryNameEqualTo(factoryName).andBanCiEqualTo(banCi).andGradeValueEqualTo(gradeValue).andStatusEqualTo(Constants.NORMAL_STATUS).andPackageStartTimeBetween(queryForm.getStartTime(), queryForm.getEndTime());
        List<ProductPackage> productPackageList = productPackageMapper.selectByExample(packageExample);
        double totalOutput = 0; // 累加实际产量
        for (ProductPackage productPackage : productPackageList) {
            ProductPackageJobExample packageJobExample = new ProductPackageJobExample();
            packageJobExample.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andProductPackageIdEqualTo(productPackage.getId()).andLabelTypeEqualTo("B").andJobStatusEqualTo("1");
            int count = productPackageJobMapper.countByExample(packageJobExample);
            //实际产量（包装数量）*500/1000
            double output = ((double) count * 500) / 1000;
            totalOutput += output; // 累加产量
        }
        BigDecimal totalOutputBigDecimal = new BigDecimal(totalOutput);
        totalOutputBigDecimal = totalOutputBigDecimal.setScale(1, RoundingMode.HALF_UP);
        return totalOutputBigDecimal.toString();
    }

    @Override
    public String printSampleInfo1(String factoryName, String gradeValue, QueryForm queryForm) throws Exception {
        ProductPackageExample packageExample = new ProductPackageExample();
        packageExample.createCriteria().andFactoryNameEqualTo(factoryName).andGradeValueEqualTo(gradeValue).andStatusEqualTo(Constants.NORMAL_STATUS).andPackageStartTimeBetween(queryForm.getStartTime(), queryForm.getEndTime());
        List<ProductPackage> productPackageList = productPackageMapper.selectByExample(packageExample);
        double totalOutput = 0; // 累加实际产量
        for (ProductPackage productPackage : productPackageList) {
            ProductPackageJobExample packageJobExample = new ProductPackageJobExample();
            packageJobExample.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andProductPackageIdEqualTo(productPackage.getId()).andLabelTypeEqualTo("B").andJobStatusEqualTo("1");
            int count = productPackageJobMapper.countByExample(packageJobExample);
            //实际产量（包装数量）*500/1000
            double output = ((double) count * 500) / 1000;
            totalOutput += output; // 累加产量
        }
        BigDecimal totalOutputBigDecimal = new BigDecimal(totalOutput);
        totalOutputBigDecimal = totalOutputBigDecimal.setScale(1, RoundingMode.HALF_UP);
        return totalOutputBigDecimal.toString();
    }


    private void setShiftTimes(QueryForm queryForm, LocalDateTime now) {
        LocalTime time = now.toLocalTime();
        if (time.isAfter(LocalTime.of(8, 0)) && time.isBefore(LocalTime.of(20, 0))) {
            // A班：早上8点到晚上8点
            LocalDateTime startTime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(8, 0));
            LocalDateTime endTime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(19, 59, 59));
            queryForm.setStartTime(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            queryForm.setEndTime(endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        } else {
            // B班：晚上8点到早上8点
            LocalDateTime startTime = LocalDateTime.of(now.toLocalDate().minusDays(1), LocalTime.of(20, 0));
            LocalDateTime endTime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(7, 59, 59));
            queryForm.setStartTime(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            queryForm.setEndTime(endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
    }

    private void handPeiTou(JSONObject roomObject, Map<String, ProductPeiTou> banliaoProductMap, SimpleDateFormat simpleDateFormat, SimpleDateFormat simpleDateFormat1) throws Exception {
        JSONArray banliaoArray = roomObject.getJSONArray("banliaolist");
        for (int j = 0; j < banliaoArray.size(); ++j) {
            JSONObject object = banliaoArray.getJSONObject(j);
            String batchnum = object.getString("batchnumstr");
            String key = batchnum + "";
            System.out.println("===============配料投料===============");
            System.out.println(object.toJSONString());
            String startTime = "";
            String endTime = "";
            String ostarttime = object.getString("ostarttime");
            if (!StringUtils.equals(ostarttime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(ostarttime)) {
                long startTimeStamp = simpleDateFormat.parse(ostarttime).getTime();
                startTime = simpleDateFormat1.format(new Date(startTimeStamp));
            }
            String oendtime = object.getString("oendtime");
            if (!StringUtils.equals(oendtime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(oendtime)) {
                long endTimeStamp = simpleDateFormat.parse(oendtime).getTime();
                endTime = simpleDateFormat1.format(new Date(endTimeStamp));
            }
            System.out.println("===============batchnum：" + batchnum + "==========startTime:" + startTime + "======endTime:" + endTime);
            ProductPeiTou productPeiTou = new ProductPeiTou();
            if (StringUtils.isNotEmpty(startTime) ) {
                productPeiTou.setChuStartTime(startTime);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                productPeiTou.setChuEndTime(endTime);
            }
            if (banliaoProductMap.containsKey(key)) {
                ProductPeiTou exist = banliaoProductMap.get(key);
                if (StringUtils.isNotEmpty(exist.getChuStartTime())) {
                    productPeiTou.setChuStartTime(exist.getChuStartTime());
                } else {
                    productPeiTou.setChuStartTime(startTime);
                }
                if (StringUtils.isNotEmpty(exist.getChuEndTime())) {
                    productPeiTou.setChuEndTime(exist.getChuEndTime());
                } else {
                    productPeiTou.setChuEndTime(endTime);
                }
            }
            if (StringUtils.isNotEmpty(productPeiTou.getChuStartTime()) && StringUtils.isNotEmpty(productPeiTou.getChuEndTime())) {
                productPeiTou.setChuStatus("1");
            }
            if (StringUtils.isNotEmpty(productPeiTou.getChuStartTime()) || StringUtils.isNotEmpty(productPeiTou.getChuEndTime())) {
                banliaoProductMap.put(key, productPeiTou);
            }
        }
    }

    private void handleChumo(JSONObject roomObject, Map<String, ProductThinPeriod> cumoProductMap, SimpleDateFormat simpleDateFormat, SimpleDateFormat simpleDateFormat1, Map<String, String> zhongzhuanMap) throws Exception {
        JSONArray cumoArray = roomObject.getJSONArray("cumolist");
        for (int j = 0; j < cumoArray.size(); ++j) {
            JSONObject object = cumoArray.getJSONObject(j);
            String batchnum = object.getString("batchnumstr");
            System.out.println("============粗磨数据==============");
            System.out.println(object.toJSONString());
            String key = batchnum + "";
            String startguan = object.getString("startguan");
            String endguan = object.getString("endguan");
            zhongzhuanMap.put(batchnum + "", endguan);

            String startTime = "";
            String endTime = "";
            String mstarttime = object.getString("mstarttime");
            String mendtime = object.getString("mendtime");
            if (!StringUtils.equals(mstarttime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(mstarttime)) {
                long startTimeStamp = simpleDateFormat.parse(mstarttime).getTime();
                startTime = simpleDateFormat1.format(new Date(startTimeStamp));
            }
            if (!StringUtils.equals(mendtime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(mendtime)) {
                long endTimeStamp = simpleDateFormat.parse(mendtime).getTime();
                endTime = simpleDateFormat1.format(new Date(endTimeStamp));
            }
            String moshaspeed = object.getString("moshaspeed");
            String moshatemp = object.getString("moshatemp");
            ProductThinPeriod productThinPeriod = new ProductThinPeriod();
            productThinPeriod.setThinStatus("1");
            productThinPeriod.setProductCode(batchnum + "");
            productThinPeriod.setThinGuanCode(startguan);
            productThinPeriod.setThinFinalCode(endguan);
            productThinPeriod.setRevoSpeed(moshaspeed);
            productThinPeriod.setBanSepeed(moshatemp);
            productThinPeriod.setResverGuan("0");
            productThinPeriod.setStartTime(startTime);
            productThinPeriod.setEndTime(endTime);
            if (cumoProductMap.containsKey(key)) {
                ProductThinPeriod exist = cumoProductMap.get(key);
                if (StringUtils.isNotEmpty(exist.getStartTime())) {
                    productThinPeriod.setStartTime(exist.getStartTime());
                } else {
                    productThinPeriod.setStartTime(startTime);
                }
                if (StringUtils.isNotEmpty(exist.getEndTime())) {
                    productThinPeriod.setEndTime(exist.getEndTime());
                } else {
                    productThinPeriod.setEndTime(endTime);
                }
                if (StringUtils.isEmpty(productThinPeriod.getThinGuanCode())) {
                    productThinPeriod.setThinGuanCode(exist.getThinGuanCode());
                }
                if (StringUtils.isEmpty(productThinPeriod.getThinFinalCode())) {
                    productThinPeriod.setThinGuanCode(exist.getThinFinalCode());
                }
                if (StringUtils.isEmpty(productThinPeriod.getRevoSpeed()) || productThinPeriod.getRevoSpeed().compareTo(exist.getRevoSpeed()) < 0) {
                    productThinPeriod.setRevoSpeed(exist.getRevoSpeed());
                }
            }
            if (StringUtils.isNotEmpty(productThinPeriod.getStartTime()) && StringUtils.isNotEmpty(productThinPeriod.getEndTime())) {
                long stime = simpleDateFormat1.parse(productThinPeriod.getStartTime()).getTime();
                long etime = simpleDateFormat1.parse(productThinPeriod.getEndTime()).getTime();
                long dist = (etime - stime) / 1000 / 60;
                productThinPeriod.setSpendTime(dist + "");
                productThinPeriod.setThinStatus("2");
                System.out.println("============粗磨数据结束=============="+productThinPeriod.getProductCode());
            }
            cumoProductMap.put(key, productThinPeriod);
        }
    }

    private void handleZhongzhuanlist(JSONObject roomObject, Map<String, String> zhongzhuanMap) {
        JSONArray zhongzhuanArray = roomObject.getJSONArray("zhongzhuanlist");
        for (int j = 0; j < zhongzhuanArray.size(); ++j) {
            JSONObject object = zhongzhuanArray.getJSONObject(j);
            String batchnum = object.getString("batchnumstr");
            String endguan = object.getString("endguan");
            if (StringUtils.isNotEmpty(endguan)) {
                zhongzhuanMap.put(batchnum + "", endguan);
            }
        }
    }


    private void handleXimo(JSONObject roomObject, Map<String, ProductThickPeriod> ximoProductMap, Map<String, ProductThickPeriodTime> ximoTimeProductMap, SimpleDateFormat simpleDateFormat, SimpleDateFormat simpleDateFormat1) throws Exception {
        JSONArray ximoArray = roomObject.getJSONArray("ximolist");
        for (int j = 0; j < ximoArray.size(); ++j) {
            JSONObject object = ximoArray.getJSONObject(j);
            System.out.println("============细磨数据==============");
            System.out.println(object.toJSONString());
            String batchnum = object.getString("batchnumstr");
            int countnum = object.getInteger("countnum");
            if (countnum == 0) {
                System.out.println("=============细磨数据的countnum等于0======" + countnum);
                continue;
            }
            String key = batchnum + "-" + countnum;

            String startTime = "";
            String endTime = "";
            String mstarttime = object.getString("mstarttime");
            String mendtime = object.getString("mendtime");
            if (!StringUtils.equals(mstarttime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(mstarttime)) {
                long startTimeStamp = simpleDateFormat.parse(mstarttime).getTime();
                startTime = simpleDateFormat1.format(new Date(startTimeStamp));
            }
            if (!StringUtils.equals(mendtime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(mendtime)) {
                long endTimeStamp = simpleDateFormat.parse(mendtime).getTime();
                endTime = simpleDateFormat1.format(new Date(endTimeStamp));
            }
            String moshaspeed = object.getString("moshaspeed");
            String moshatemp = object.getString("moshatemp");
            String startguan = object.getString("startguan");
            String endguan = object.getString("endguan");
            String ximoxian = object.getString("ximoxian");

            ProductThickPeriodTime productThickPeriodTime = new ProductThickPeriodTime();
            productThickPeriodTime.setStartGuan(startguan);
            productThickPeriodTime.setEndGuan(endguan);
            productThickPeriodTime.setNumberTime(countnum + "");

            productThickPeriodTime.setRevoSpeed(moshaspeed);
            productThickPeriodTime.setTemperature(moshatemp);
            productThickPeriodTime.setXimoLine(ximoxian);
            productThickPeriodTime.setProductCode(batchnum + "");
            if (ximoTimeProductMap.containsKey(key)) {
                ProductThickPeriodTime exist = ximoTimeProductMap.get(key);
                if (StringUtils.isNotEmpty(exist.getStartTime())) {
                    productThickPeriodTime.setStartTime(exist.getStartTime());
                } else {
                    productThickPeriodTime.setStartTime(startTime);
                }
                if (StringUtils.isNotEmpty(exist.getEndTime())) {
                    productThickPeriodTime.setEndTime(exist.getEndTime());
                } else {
                    productThickPeriodTime.setEndTime(endTime);
                }
                if (StringUtils.isEmpty(productThickPeriodTime.getRevoSpeed()) || productThickPeriodTime.getRevoSpeed().compareTo(exist.getRevoSpeed()) < 0) {
                    productThickPeriodTime.setRevoSpeed(exist.getRevoSpeed());
                }
                if (StringUtils.isEmpty(productThickPeriodTime.getTemperature()) || productThickPeriodTime.getTemperature().compareTo(exist.getTemperature()) < 0) {
                    productThickPeriodTime.setTemperature(exist.getRevoSpeed());
                }
                if (StringUtils.isEmpty(productThickPeriodTime.getXimoLine())) {
                    productThickPeriodTime.setXimoLine(exist.getXimoLine());
                }
            }
            ximoTimeProductMap.put(key, productThickPeriodTime);
            ProductThickPeriod productThickPeriod = new ProductThickPeriod();
            if (countnum == 1) {
                productThickPeriod.setStartTime(startTime);
                productThickPeriod.setThickGuanCode(startguan);
            }
            productThickPeriod.setXimoLine(productThickPeriodTime.getXimoLine());
            if (ximoProductMap.containsKey(batchnum + "")) {
                ProductThickPeriod existThick = ximoProductMap.get(batchnum + "");
                if (StringUtils.isEmpty(productThickPeriod.getXimoLine())) {
                    productThickPeriod.setXimoLine(existThick.getXimoLine());
                }
            }
            ximoProductMap.put(batchnum + "", productThickPeriod);
        }
    }

    private void handleChuci(JSONObject roomObject, Map<String, ProductChuciPeriod> chuciProductMap, SimpleDateFormat simpleDateFormat, SimpleDateFormat simpleDateFormat1) throws Exception {
        JSONArray chucilist = roomObject.getJSONArray("chucilist");
        for (int j = 0; j < chucilist.size(); ++j) {
            System.out.println("=================chucilist==============");
            JSONObject object = chucilist.getJSONObject(j);
            System.out.println(object.toJSONString());
            String batchnum = object.getString("batchnumstr");
            String key = batchnum + "";
            String startguan = object.getString("startguan");
            String endguan = object.getString("endguan");
            ProductChuciPeriod productChuciPeriod = new ProductChuciPeriod();

            String startTime = "";
            String endTime = "";
            String mstarttime = object.getString("mstarttime");
            String mendtime = object.getString("mendtime");
            if (!StringUtils.equals(mstarttime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(mstarttime)) {
                long startTimeStamp = simpleDateFormat.parse(mstarttime).getTime();
                startTime = simpleDateFormat1.format(new Date(startTimeStamp));
//                productChuciPeriod.setStartTime(simpleDateFormat1.format(new Date(startTime)));
            }
            if (!StringUtils.equals(mendtime, "0001-01-01T00:00:00") && StringUtils.isNotEmpty(mendtime)) {
                long endTimeStamp = simpleDateFormat.parse(mendtime).getTime();
                endTime = simpleDateFormat1.format(new Date(endTimeStamp));
//                productChuciPeriod.setEndTime(simpleDateFormat1.format(new Date(endTimeStamp)));
            }
            productChuciPeriod.setStartTime(startTime);
            productChuciPeriod.setEndTime(endTime);
            productChuciPeriod.setThinGuanCode(startguan);
            productChuciPeriod.setChuciMachine(endguan);
            productChuciPeriod.setChuciStatus("1");
            productChuciPeriod.setProductCode(batchnum + "");

            if (chuciProductMap.containsKey(key)) {
                ProductChuciPeriod exist = chuciProductMap.get(key);
                if(StringUtils.isEmpty(productChuciPeriod.getStartTime())){
                    productChuciPeriod.setStartTime(exist.getStartTime());
                }
                if(StringUtils.isEmpty(productChuciPeriod.getEndTime())){
                    productChuciPeriod.setEndTime(exist.getEndTime());
                }
                if(StringUtils.isEmpty(productChuciPeriod.getThinGuanCode())){
                    productChuciPeriod.setThinGuanCode(exist.getThinGuanCode());
                }
                if(StringUtils.isEmpty(productChuciPeriod.getChuciMachine())){
                    productChuciPeriod.setChuciMachine(exist.getChuciMachine());
                }
            }
            if (StringUtils.isNotEmpty(productChuciPeriod.getStartTime()) && StringUtils.isNotEmpty(productChuciPeriod.getEndTime())) {
                long stamp = simpleDateFormat1.parse(productChuciPeriod.getEndTime()).getTime() -  simpleDateFormat1.parse(productChuciPeriod.getStartTime()).getTime();
                long dist = stamp / 1000 / 60;
                productChuciPeriod.setSpendTime(dist + "");
                productChuciPeriod.setChuciStatus("2");
            }
            chuciProductMap.put(key, productChuciPeriod);
        }
    }

    private void handleChengpin(JSONObject roomObject, Map<String, JSONObject> chengpingMap) {
        JSONArray chengpingArray = roomObject.getJSONArray("zuizhongchengpinglist");
        for (int j = 0; j < chengpingArray.size(); ++j) {
            JSONObject object = chengpingArray.getJSONObject(j);
            System.out.println("=======================最终成品数据=================");
            System.out.println(object.toJSONString());
            String batchnum = object.getString("cpbatchnumstr");
            String chengpingnum = object.getString("chengpingnum");
            if (StringUtils.isNotEmpty(chengpingnum)) {
                chengpingMap.put(batchnum , object);
            }
        }
    }

    //处理露点温度
    public void handLuTemp() throws Exception {
        Map<String, String> tempMap = Maps.newHashMap();
        for (int i = 1; i <= 6; i++) {
            String key = "LD" + i;
            tempMap.put(i + "", "");
            long roomSize = redisTemplate.opsForList().size(key);
            if (roomSize > 0) {
                for (int m = 0; m < roomSize; m++) {
                    Object value = redisTemplate.opsForList().rightPop(key);
                    if (null == value) {
                        continue;
                    }
                    JSONObject json = JSON.parseObject(value.toString());
                    if (StringUtils.isEmpty(json.getString("Temperature"))) {
                        continue;
                    }
                    tempMap.put(i + "", json.getString("Temperature"));
                }

            }
        }
        List<ProductPackageJob> jobs = productPackageService.getProductJobsNotFinsh();
        List<ProductPackageJob> updates = Lists.newArrayList();
        for (ProductPackageJob job : jobs) {
            if (tempMap.containsKey(job.getPackageRoom()) && StringUtils.isNotEmpty(tempMap.get(job.getPackageRoom()))) {
                job.setLuTemp(tempMap.get(job.getPackageRoom()));
                updates.add(job);
            }
        }
        if (CollectionsUtil.isNotEmpty(updates)) {
            productPackageService.updateProductJobLuTemp(jobs);
        }
    }

    @Scheduled(cron = "0 0 */1 * * ?")
    public void actionFenjiRecord() throws Exception {
        List<ProductDianciFenjiRecord> fenjiRecords = Lists.newArrayList();
        //分级
        this.handleFenji("16-1", fenjiRecords);
        this.handleFenji("16-2", fenjiRecords);
        if (CollectionsUtil.isNotEmpty(fenjiRecords)) {
            productDianciFenjiRecordMapper.batchInsertDianciFenjiRecords(fenjiRecords);
        }
    }


    @Scheduled(cron = "0 */2 * * * ?")
    public void actionRedis() throws Exception {

        List<String> allRedisList = Lists.newArrayList();
        long roomSize = redisTemplate.opsForList().size("161");
//        List<String> redisList = redisTemplate.opsForList().range("161", 0, roomSize);
//        if (CollectionsUtil.isNotEmpty(redisList)) {
//            allRedisList.addAll(redisList);
//        }
        for (int i = 0; i < roomSize; i++) {
            Object value = redisTemplate.opsForList().rightPop("161");
            if (null != value) {
                allRedisList.add(value.toString());
            }
        }


        long roomSize2 = redisTemplate.opsForList().size("162");
//        List<String> redisList2 = redisTemplate.opsForList().range("162", 0, roomSize2);
//        if (CollectionsUtil.isNotEmpty(redisList2)) {
//            allRedisList.addAll(redisList2);
//        }


        for (int i = 0; i < roomSize2; i++) {
            Object value = redisTemplate.opsForList().rightPop("162");
            if (null != value) {
                allRedisList.add(value.toString());
            }
        }

        List<JSONObject> redisJsons = Lists.newLinkedList();
        for (int i = 0; i < allRedisList.size(); ++i) {
            try {
                JSONObject roomObject = JSON.parseObject(allRedisList.get(i));
                redisJsons.add(roomObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, ProductPeiTou> banliaoProductMap = Maps.newHashMap();
        Map<String, ProductThinPeriod> cumoProductMap = Maps.newHashMap();

        //中转
        Map<String, String> zhongzhuanMap = Maps.newHashMap();

        Map<String, ProductThickPeriodTime> ximoTimeProductMap = Maps.newHashMap();
        Map<String, ProductThickPeriod> ximoProductMap = Maps.newHashMap();

        Map<String, ProductChuciPeriod> chuciMap = Maps.newHashMap();

        Map<String, JSONObject> chengpingMap = Maps.newHashMap();

        for (int i = 0; i < redisJsons.size(); ++i) {
            JSONObject roomObject = redisJsons.get(i);
            try {
                this.handPeiTou(roomObject, banliaoProductMap, simpleDateFormat, simpleDateFormat1);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("========handPeiTou error=========");
                System.out.println(roomObject.toJSONString());
            }
            try {
                this.handleChumo(roomObject, cumoProductMap, simpleDateFormat, simpleDateFormat1, zhongzhuanMap);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("========handleChumo error=========");
                System.out.println(roomObject.toJSONString());
            }
//                this.handleZhongzhuanlist(roomObject, zhongzhuanMap);
            try {
                this.handleXimo(roomObject, ximoProductMap, ximoTimeProductMap, simpleDateFormat, simpleDateFormat1);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("========handleXimo error=========");
                System.out.println(roomObject.toJSONString());
            }
            try {
                this.handleChuci(roomObject, chuciMap, simpleDateFormat, simpleDateFormat1);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("========handleChuci error=========");
                System.out.println(roomObject.toJSONString());
            }
            try {
                this.handleChengpin(roomObject, chengpingMap);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("========handleChengpin error=========");
                System.out.println(roomObject.toJSONString());
            }
        }
        try {
            //更新配料投料
            this.updatePeiTouByRedisMessage(banliaoProductMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            //更新粗磨
            this.updateThinByRedisMessage(cumoProductMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            //更新细磨
            this.updateXimoByRedisMessage(ximoProductMap, ximoTimeProductMap, zhongzhuanMap);
        } catch (Exception e) {
            System.out.println("=======updateXimoByRedisMessage error=========");
            e.printStackTrace();
        }

        try {
            //除磁
            this.updateChuciByRedisMessage(chuciMap, chengpingMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            //干燥
            this.handleGangzao();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            //烧结
            this.handSaojie();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            //处理露点温度
            this.handLuTemp();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void handleFenji(String factoryName, List<ProductDianciFenjiRecord> fenjiRecords) {
        String room = factoryName.split("-")[0] + factoryName.split("-")[1];
        Map<String, ProductDianciFenjiRecord> fenjiMap = Maps.newHashMap();
        for (int i = 19; i <= 33; i++) {
            String key = room + "-F" + i;
            List<String> redis = Lists.newArrayList();
            long roomSize = redisTemplate.opsForList().size(key);
            for (int m = 0; m < roomSize; m++) {
                Object value = redisTemplate.opsForList().rightPop(key);
                if (null != value) {
                    redis.add(value.toString());
                }
            }

            if (CollectionsUtil.isEmpty(redis)) {
                continue;
            }
            Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
            for (int j = 0; j < redis.size(); ++j) {
                try {
                    String fenjiRoom = "";
                    System.out.println("===============分级数据=============");
                    System.out.println(redis.get(j));
                    JSONObject roomObject = JSON.parseObject(redis.get(j));
                    String fenjinum = roomObject.getString("fenjinum");
                    String timeStamp = roomObject.getString("TimeStamp");
                    if (fenjiMap.containsKey(fenjinum) && timeStamp.compareTo(fenjiMap.get(fenjinum).getTimestamp()) < 0) {
                        continue;
                    }
                    String jialiaohz = roomObject.getString("jialiaohz");
                    String jialiaoele = roomObject.getString("jialiaoele");
                    String fenjihz = roomObject.getString("fenjihz");
                    String fenjiele = roomObject.getString("fenjiele");
                    String airtemp = roomObject.getString("airtemp");
                    String pressure = roomObject.getString("pressure");
                    String crushp = roomObject.getString("crushp");
                    String dust = roomObject.getString("dust");
                    String emrdust = roomObject.getString("emrdust");
                    String temp = roomObject.getString("temp");
                    String oxygen = roomObject.getString("oxygen");
                    ProductDianciFenjiRecord record = new ProductDianciFenjiRecord();
                    record.setId(CommonUtil.generateRandomNum("fjrecord-"));
                    record.setDutyDay(dutyMap.get("dutyDay"));
                    record.setBanCi(StringUtils.equals(dutyMap.get("whiteDay"), "1") ? "A" : "B");
                    record.setFactoryName(factoryName);
                    record.setFenjiCode(fenjinum);
                    record.setJialiaoPinLv(jialiaohz);
                    record.setJialiaDianLiu(jialiaoele);
                    record.setFenjiPinLv(fenjihz);
                    record.setFenjiDianLiu(fenjiele);
                    record.setQiWen(airtemp);
                    record.setFuYa(pressure);
                    record.setPa(crushp);
                    record.setChuPa(dust);
                    record.setYingjiChuPa(emrdust);
                    record.setWenDu(temp);
                    record.setHanYang(oxygen);
                    if (Integer.parseInt(fenjinum) <= 5) {
                        fenjiRoom = "1";
                    } else if (Integer.parseInt(fenjinum) <= 10) {
                        fenjiRoom = "2";
                    } else {
                        fenjiRoom = "3";
                    }
                    record.setTimestamp(timeStamp);
                    record.setFenjiRoom(fenjiRoom);
                    fenjiMap.put(fenjinum, record);
                } catch (Exception e) {

                }
            }
        }
        for (String key : fenjiMap.keySet()) {
            fenjiRecords.add(fenjiMap.get(key));
        }
    }

    private void updatePeiTouByRedisMessage(Map<String, ProductPeiTou> banliaoProductMap) throws Exception {
        List<String> productCodes = Lists.newArrayList();
        for (String key : banliaoProductMap.keySet()) {
            productCodes.add(key);
        }
        if (CollectionsUtil.isEmpty(productCodes)) {
            return;
        }
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andProductCodeIn(productCodes);
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(productPeiTous)) {
            return;
        }

        List<ProductPeiTou> updateList = Lists.newArrayList();
        for (ProductPeiTou peiTou : productPeiTous) {
            if (StringUtils.isNotEmpty(peiTou.getChuStartTime()) && StringUtils.isNotEmpty(peiTou.getChuEndTime())) {
                continue;
            }
            ProductPeiTou update = new ProductPeiTou();
            update.setId(peiTou.getId());
            String productCode = peiTou.getProductCode();
            ProductPeiTou mapObj = banliaoProductMap.get(productCode);
            update.setChuStartTime(mapObj.getChuStartTime());
            update.setChuEndTime(mapObj.getChuEndTime());
            if (StringUtils.isNotEmpty(mapObj.getChuStartTime()) && StringUtils.isNotEmpty(mapObj.getChuEndTime())) {
                update.setChuStatus("1");
            }
            updateList.add(update);
        }
        if (CollectionsUtil.isNotEmpty(updateList)) {
            productPeiTouMapper.batchUpdatePeiTous(updateList);
        }
    }

    private void updateThinByRedisMessage(Map<String, ProductThinPeriod> cumoProductMap) throws Exception {
        List<String> productCodes = Lists.newArrayList();
        for (String key : cumoProductMap.keySet()) {
            productCodes.add(key);
        }
        if (CollectionsUtil.isEmpty(productCodes)) {
            return;
        }
        List<ProductThinPeriod> productThinPeriods = productThinPeriodService.getProductThinPeriodListByCodes(productCodes);
        List<ProductThinPeriod> updates = Lists.newArrayList();
        for (ProductThinPeriod productThinPeriod : productThinPeriods) {
            if (StringUtils.equals(productThinPeriod.getThinStatus(), "2")) {
                continue;
            }
            String productCode = productThinPeriod.getProductCode();
            ProductThinPeriod mapObj = cumoProductMap.get(productCode);
            ProductThinPeriod update = new ProductThinPeriod();
            update.setId(productThinPeriod.getId());
            update.setThinGuanCode(mapObj.getThinGuanCode());
            update.setThinFinalCode(mapObj.getThinFinalCode());
            update.setStartTime(mapObj.getStartTime());
            update.setEndTime(mapObj.getEndTime());
            if (StringUtils.isNotEmpty(mapObj.getRevoSpeed())) {
                update.setRevoSpeed(mapObj.getRevoSpeed());
            }
            update.setSpendTime(mapObj.getSpendTime());
            update.setResverGuan(mapObj.getResverGuan());
            update.setThinStatus(mapObj.getThinStatus());
            updates.add(update);
        }
        if(CollectionsUtil.isNotEmpty(updates)){
            productThinPeriodService.updateBatchProductThinPeriod(updates);

        }
    }

    private void updateXimoByRedisMessage(Map<String, ProductThickPeriod> ximoProductMap, Map<String, ProductThickPeriodTime> ximoTimeProductMap, Map<String, String> zhongzhuanMap) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String today = simpleDateFormat.format(new Date());
        List<ProductThickPeriod> productThickPeriods = productThickPeriodService.getProductThickPeriodListByStatus();
        if (CollectionsUtil.isEmpty(productThickPeriods)) {
            return;
        }
        List<ProductThickPeriod> updates = Lists.newArrayList();
        List<ProductThickPeriodTime> timeUpdates = Lists.newArrayList();

        for (ProductThickPeriod thickPeriod : productThickPeriods) {
            List<ProductThickPeriodTime> timeList = thickPeriod.getProductThickPeriodTimes();
            String productCode = thickPeriod.getProductCode();
            String thickStatus = thickPeriod.getThickStatus();
            ProductThickPeriod update = new ProductThickPeriod();
            if (zhongzhuanMap.containsKey(productCode)) {
                update.setThinFinalGuan(zhongzhuanMap.get(productCode));
            }
            update.setId(thickPeriod.getId());
            if (ximoProductMap.containsKey(productCode)) {
                ProductThickPeriod objMap = ximoProductMap.get(productCode);
                update.setStartTime(objMap.getStartTime());
                update.setXimoLine(objMap.getXimoLine());
                update.setThickGuanCode(objMap.getThickGuanCode());
                update.setThickStatus("1");
                updates.add(update);
            } else if (StringUtils.equals(thickStatus, "1") && !ximoProductMap.containsKey(productCode)) {
                //没有继续收到消息 默认为细磨已经结束
                if (CollectionsUtil.isNotEmpty(timeList)) {
                    ProductThickPeriodTime latest = timeList.get(timeList.size() - 1);
                    if (StringUtils.isEmpty(latest.getEndTime())) {
                        latest.setEndTime(today);
                    }
                    String resverGuan = "0";
                    String startGuan = timeList.get(0).getStartGuan();
                    String endGuan = timeList.get(0).getEndGuan();
                    String startTime = timeList.get(0).getStartTime();
                    for (ProductThickPeriodTime periodTime : timeList) {
                        if (!StringUtils.equals(periodTime.getStartGuan(), startGuan) || !StringUtils.equals(periodTime.getEndGuan(), endGuan)) {
                            resverGuan = "1";
                        }
                    }
                    update.setEndTime(latest.getEndTime());
                    update.setThickFinalGuan(latest.getEndGuan());
                    try {
                        long dist = simpleDateFormat.parse(latest.getEndTime()).getTime() - simpleDateFormat.parse(startTime).getTime();
                        update.setSpendTime((dist / 1000) + "");
                    }catch (Exception e){
                        System.out.println("productCode :"+productCode +"starttime is "+startTime +"endtime is:"+update.getEndTime());
                        continue;
                    }
                    update.setResverGuan(resverGuan);
                    update.setThickStatus("2");
                    updates.add(update);
                }
            }

            for (ProductThickPeriodTime thickPeriodTime : timeList) {
                String timeKey = thickPeriodTime.getProductCode() + "-" + thickPeriodTime.getNumberTime();
                if (ximoTimeProductMap.containsKey(timeKey)) {
                    ProductThickPeriodTime existTime = ximoTimeProductMap.get(timeKey);
                    if (StringUtils.isEmpty(thickPeriodTime.getStartTime())) {
                        thickPeriodTime.setStartTime(existTime.getStartTime());
                    }
                    if (StringUtils.isEmpty(thickPeriodTime.getEndTime())) {
                        thickPeriodTime.setEndTime(existTime.getEndTime());
                    }
                    if (StringUtils.isEmpty(thickPeriodTime.getStartGuan())) {
                        thickPeriodTime.setStartGuan(existTime.getStartGuan());
                    }
                    if (StringUtils.isEmpty(thickPeriodTime.getEndGuan())) {
                        thickPeriodTime.setEndGuan(existTime.getEndGuan());
                    }
                    if (StringUtils.isEmpty(thickPeriodTime.getRevoSpeed())) {
                        thickPeriodTime.setRevoSpeed(existTime.getRevoSpeed());
                    }
                    if (StringUtils.isEmpty(thickPeriodTime.getBanSpeed())) {
                        thickPeriodTime.setBanSpeed(existTime.getBanSpeed());
                    }
                    if (StringUtils.isEmpty(thickPeriodTime.getTemperature())) {
                        thickPeriodTime.setTemperature(existTime.getTemperature());
                    }
                    thickPeriodTime.setNumberTime(existTime.getNumberTime());
                    timeUpdates.add(thickPeriodTime);
                    ximoTimeProductMap.remove(timeKey);
                }
            }

            for (String key1 : ximoTimeProductMap.keySet()) {
                String code = key1.split("-")[0];
                if (StringUtils.equals(thickPeriod.getProductCode(), code)) {
                    ProductThickPeriodTime mapObj = ximoTimeProductMap.get(key1);
                    ProductThickPeriodTime newTime = new ProductThickPeriodTime();
                    newTime.setThickId(thickPeriod.getId());
                    newTime.setStartTime(mapObj.getStartTime());
                    newTime.setEndTime(mapObj.getEndTime());
                    newTime.setStartGuan(mapObj.getStartGuan());
                    newTime.setEndGuan(mapObj.getEndGuan());
                    newTime.setRevoSpeed(mapObj.getRevoSpeed());
                    newTime.setBanSpeed(mapObj.getBanSpeed());
                    newTime.setTemperature(mapObj.getTemperature());
                    newTime.setNumberTime(mapObj.getNumberTime());
                    timeUpdates.add(newTime);
                    ximoTimeProductMap.remove(code);
                }
            }

        }
        if (CollectionsUtil.isNotEmpty(updates)) {
            String resp = productThickPeriodService.updateBatchProductThickPeriod(updates);
            System.out.println("======updateBatchProductThickPeriod========"+resp+"  size:"+updates.size());
        }
        if (CollectionsUtil.isNotEmpty(timeUpdates)) {
            String resp = productThickPeriodService.updateBatchProductThickPeriodTime(timeUpdates);
            System.out.println("======updateBatchProductThickPeriodTime========"+resp+"  size:"+timeUpdates.size());
        }
    }

    private void updateChuciByRedisMessage(Map<String, ProductChuciPeriod> chuciMap, Map<String, JSONObject> chengpingMap) throws Exception {
        List<String> productCodes = Lists.newArrayList();
        for (String key : chuciMap.keySet()) {
            productCodes.add(key);
        }
        for (String key : chengpingMap.keySet()) {
            productCodes.add(key);
        }
        if (CollectionsUtil.isEmpty(productCodes)) {
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ProductChuciPeriod> productChuciPeriods = productChuciPeriodService.getProductChuciPeriodListByCodes(productCodes);
        List<ProductChuciPeriod> updates = Lists.newArrayList();
        for (ProductChuciPeriod productChuciPeriod : productChuciPeriods) {
            String productCode = productChuciPeriod.getProductCode();
            ProductChuciPeriod update = new ProductChuciPeriod();
            update.setId(productChuciPeriod.getId());
            if (chuciMap.containsKey(productCode)) {
                ProductChuciPeriod mapObj = chuciMap.get(productCode);
                System.out.println("除磁更新的批次号：" + productCode);
                System.out.println("除磁更新的id：" + productChuciPeriod.getId());
                System.out.println("除磁更新的ThinGuanCode：+" + mapObj.getThinGuanCode());
                System.out.println("除磁更新的StartTime：+" + mapObj.getStartTime());
                System.out.println("除磁更新的EndTime：+" + mapObj.getEndTime());
                System.out.println("除磁更新的ChuciStatus：+" + mapObj.getChuciStatus());
                update.setThinGuanCode(mapObj.getThinGuanCode());
                update.setChuciMachine(mapObj.getChuciMachine());
                update.setStartTime(mapObj.getStartTime());
                update.setEndTime(mapObj.getEndTime());
                update.setSpendTime(mapObj.getSpendTime());
                update.setChuciStatus(mapObj.getChuciStatus());

            }
            if (chengpingMap.containsKey(productCode)) {
                System.out.println("成品包含的批次号：+" + productCode + "chengpingnum:" + chengpingMap.get(productCode).getString("chengpingnum") + "cstarttime:" + chengpingMap.get(productCode).getString("cstarttime"));
                update.setChengGuanCode(chengpingMap.get(productCode).getString("chengpingnum"));
                Date startTime = simpleDateFormat.parse(chengpingMap.get(productCode).getString("cstarttime"));
                System.out.println("批次号：" + productCode + "的成品罐结束时间为：" + chengpingMap.get(productCode).getString("cstarttime"));
                if (!StringUtils.equals(chengpingMap.get(productCode).getString("cstarttime"), "0001-01-01T00:00:00")) {
                    Date endTime = simpleDateFormat.parse(chengpingMap.get(productCode).getString("cendtime"));
                    update.setChengEndTime(simpleDateFormat1.format(endTime));
                }
                update.setChengStartTime(simpleDateFormat1.format(startTime));
                update.setChuciStatus("2");
                if (StringUtils.isEmpty(productChuciPeriod.getEndTime())) {
                    productChuciPeriod.setEndTime(simpleDateFormat1.format(startTime));
                    String chuciStartTime = productChuciPeriod.getStartTime();
                    if (StringUtils.isNotEmpty(chuciStartTime)) {
                        long stime = simpleDateFormat1.parse(chuciStartTime).getTime();
                        long etime = startTime.getTime();
                        long dist = (etime - stime) / 1000 / 60;
                        update.setSpendTime(dist + "");
                    }
                }
            }
            System.out.println("==============update chucidata==========");
            System.out.println(update);
            updates.add(update);
        }
        productChuciPeriodService.updateBatchProductChuciPeriod(updates);
    }

    public void handleGangzao() throws Exception {
        List<ProductGzPeriod> productGzPeriods = productGzPeriodService.getProductGzPeriodByStatus();
        Pattern pattern = Pattern.compile("\\d+");
        Map<String, List<ProductGzPeriod>> prodMap = Maps.newHashMap();
        for (ProductGzPeriod productGzPeriod : productGzPeriods) {
            String factoryName = productGzPeriod.getFactoryName();
            String gzGuanCode = productGzPeriod.getGzGuanCode();
            Matcher matcher = pattern.matcher(gzGuanCode);
            int numGuanCode = 0;
            while (matcher.find()) {
                numGuanCode = Integer.parseInt(matcher.group());
            }
            String key = factoryName.split("-")[0] + factoryName.split("-")[1] + "-" + numGuanCode + "#";
            if (prodMap.containsKey(key)) {
                prodMap.get(key).add(productGzPeriod);
            } else {
                List<ProductGzPeriod> pod = Lists.newArrayList();
                pod.add(productGzPeriod);
                prodMap.put(key, pod);
            }
        }
        List<ProductGzPeriodSl> gzPeriodSl = Lists.newArrayList();
        List<ProductGzPeriodSl> gzUpdatePeriodSls = Lists.newArrayList();
        List<ProductGzPeriod> updateGzPeriods = Lists.newArrayList();
        this.getGzNeedUpdateDatas(gzPeriodSl, gzUpdatePeriodSls, prodMap, "161",updateGzPeriods);
        this.getGzNeedUpdateDatas(gzPeriodSl, gzUpdatePeriodSls, prodMap, "162",updateGzPeriods);
        if (CollectionsUtil.isNotEmpty(gzPeriodSl)) {
            String resp = productGzPeriodService.insertBatchProductGzSl(gzPeriodSl);
            if (StringUtils.isNotEmpty(resp)) {
                return;
            }
        }
        if (CollectionsUtil.isNotEmpty(gzUpdatePeriodSls)) {
            productGzPeriodService.insertBatchProductGzSl(gzUpdatePeriodSls);
        }

        if(CollectionsUtil.isNotEmpty(updateGzPeriods)){
            productGzPeriodService.updateBatchProductGzPeriod(updateGzPeriods);
        }

    }

    public void handSaojie() throws Exception {
        List<ProductSaojiePeriod> productSaojiePeriods = productSaojiePeriodService.getProductSaojiePeriodsByStatus();
        Map<String, List<ProductSaojieJob>> saojieJobMap = Maps.newHashMap();
        for (ProductSaojiePeriod saojiePeriod : productSaojiePeriods) {
            List<ProductSaojieJob> jobs = saojiePeriod.getProductSaojieJobs();
            String factoryName = saojiePeriod.getFactoryName();
            String factoryKey = factoryName.split("-")[0] + factoryName.split("-")[1];
            for (ProductSaojieJob job : jobs) {
                String yaoGuanCode = job.getYaoGuanCode();
                int numYao = Integer.parseInt(yaoGuanCode);
                double up = numYao / 2.0;
                int line = (int) Math.ceil(up);
                int code = numYao % 2 == 0 ? 2 : 1;
                String key = factoryKey + "-" + line + "" + code;
                if (saojieJobMap.containsKey(key)) {
                    saojieJobMap.get(key).add(job);
                } else {
                    List<ProductSaojieJob> adds = Lists.newArrayList();
                    adds.add(job);
                    saojieJobMap.put(key, adds);
                }
            }
        }
        List<ProductSaojieJob> needUpdateJobs = Lists.newArrayList();
        List<ProductSaojieGuan> needUpdateGuans = Lists.newArrayList();
        this.getShaojieNeedUpdateDatas(needUpdateJobs, saojieJobMap, "161", needUpdateGuans, "16-1");
        this.getShaojieNeedUpdateDatas(needUpdateJobs, saojieJobMap, "162", needUpdateGuans, "16-2");
        if (CollectionsUtil.isNotEmpty(needUpdateJobs)) {
            productSaojiePeriodService.updateBatchProductSaojieJobByRedis(needUpdateJobs);
        }
        if (CollectionsUtil.isNotEmpty(needUpdateGuans)) {
            productSaojieGuanService.updateBatchProductSaojieGuans(needUpdateGuans);
        }
    }

    private void getGzNeedUpdateDatas(List<ProductGzPeriodSl> gzPeriodSls, List<ProductGzPeriodSl> gzUpdatePeriodSls, Map<String, List<ProductGzPeriod>> prodMap, String room,List<ProductGzPeriod> updateGzPeriods) throws Exception {
        for (int i = 1; i <= 6; i++) {
            String key = room + "-" + i + "#";
            List<String> redis = Lists.newArrayList();
            long roomSize = redisTemplate.opsForList().size(key);
            for (int m = 0; m < roomSize; m++) {
                Object value = redisTemplate.opsForList().rightPop(key);
                if (null != value) {
                    redis.add(value.toString());
                }

            }

//            List<String> redis = redisTemplate.opsForList().range(key, 0, roomSize);
//            redisTemplate.opsForList().trim(key, roomSize, 0);
            if (CollectionsUtil.isEmpty(redis)) {
                continue;
            }
            if (!prodMap.containsKey(key)) {
                continue;
            }
            List<JSONObject> redisJsons = Lists.newLinkedList();
            for (int j = 0; j < redis.size(); ++j) {
                try {
                    System.out.println("===============喷水喷料=============");
                    System.out.println(redis.get(j));
                    JSONObject roomObject = JSON.parseObject(redis.get(j));
                    redisJsons.add(roomObject);
                } catch (Exception e) {

                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            Collections.sort(redisJsons, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    String timeStamp1 = o1.getString("TimeStamp");
                    String timeStamp2 = o2.getString("TimeStamp");
                    if (StringUtils.isEmpty(timeStamp1)) {
                        return 1;
                    } else if (StringUtils.isEmpty(timeStamp2)) {
                        return -1;
                    }
                    long timeStampLong1 = 0;
                    long timeStampLong2 = 0;
                    try {
                        timeStampLong1 = (simpleDateFormat.parse(timeStamp1).getTime()) / 1000;
                        timeStampLong2 = (simpleDateFormat.parse(timeStamp2).getTime()) / 1000;
                    } catch (Exception e) {

                    }
                    return (int) (timeStampLong1 - timeStampLong2);
                }
            });

            String firstWaterEndTime = "";
            String firstliaoEndTime = "";

            String waterStartTime = "";
            String liaoStartTime = "";

            //进风温度
             String jinFenTemp = "";
            //排风温度
             String paiFenTemp= "";
            //雾化器温度
             String wuHuaTemp= "";
            //雾化器油压
             String wuHuaPa= "";
            //水罐液位
             String yeWei= "";
            //供料流量
             String liuLiang= "";
            //雾化器转速
             String zhuanSu= "";
            //送风机风速
             String songFenJi= "";
            for (int k = 0; k < redisJsons.size(); k++) {
                String Penshui = redisJsons.get(k).getString("Penshui");
                String Penliao = redisJsons.get(k).getString("Penliao");
                if (StringUtils.equals(Penshui, "false") && StringUtils.isEmpty(firstWaterEndTime)) {
                    firstWaterEndTime = redisJsons.get(k).getString("TimeStamp");
                }
                if (StringUtils.equals(Penshui, "true") && StringUtils.isEmpty(waterStartTime)) {
                    waterStartTime = redisJsons.get(k).getString("TimeStamp");
                }
                if (StringUtils.equals(Penliao, "false") && StringUtils.isEmpty(firstliaoEndTime)) {
                    firstliaoEndTime = redisJsons.get(k).getString("TimeStamp");
                }

                if (StringUtils.equals(Penliao, "true") && StringUtils.isEmpty(liaoStartTime)) {
                    liaoStartTime = redisJsons.get(k).getString("TimeStamp");
                }
                String v1 =  redisJsons.get(k).getString("JinfengTemp");
                String v2 =  redisJsons.get(k).getString("PaifengTemp");
                String v3 =  redisJsons.get(k).getString("WuhuaTemp");
                String v4 =  redisJsons.get(k).getString("WuhuaPressure");
                String v5 =  redisJsons.get(k).getString("Yewei");
                String v6 =  redisJsons.get(k).getString("Liuliang");
                String v7 =  redisJsons.get(k).getString("Zhuansu");
                String v8 =  redisJsons.get(k).getString("Songfengji");
                if(StringUtils.isNotEmpty(v1)){
                    jinFenTemp = v1;
                }
                if(StringUtils.isNotEmpty(v2)){
                    paiFenTemp = v2;
                }
                if(StringUtils.isNotEmpty(v3)){
                    wuHuaTemp = v3;
                }
                if(StringUtils.isNotEmpty(v4)){
                    wuHuaPa = v4;
                }
                if(StringUtils.isNotEmpty(v5)){
                    yeWei = v5;
                }
                if(StringUtils.isNotEmpty(v6)){
                    liuLiang = v6;
                }
                if(StringUtils.isNotEmpty(v7)){
                    zhuanSu = v7;
                }
                if(StringUtils.isNotEmpty(v8)){
                    songFenJi = v8;
                }
            }

            List<ProductGzPeriod> productGzPeriods = prodMap.get(key);
            for (ProductGzPeriod period : productGzPeriods) {
                List<ProductGzPeriodSl> gzPeriodSlList = period.getProductGzPeriodSls();

                String factoryName = period.getFactoryName();
                String factoryConvert = factoryName.split("-")[0] + factoryName.split("-")[1] + period.getGzGuanCode();
                System.out.println("=============factoryConvert===========" + factoryConvert + " =====room====" + (room + i));
                if (!StringUtils.equals(factoryConvert, room + i)) {
                    continue;
                }
                ProductGzPeriod update = new ProductGzPeriod();
                update.setId(period.getId());
                update.setJinFenTemp(jinFenTemp);
                update.setPaiFenTemp(paiFenTemp);
                update.setWuHuaPa(wuHuaPa);
                update.setWuHuaTemp(wuHuaTemp);
                update.setYeWei(yeWei);
                update.setLiuLiang(liuLiang);
                update.setZhuanSu(zhuanSu);
                update.setSongFenJi(songFenJi);
                updateGzPeriods.add(update);

                ProductGzPeriodSl shui = new ProductGzPeriodSl();
                ProductGzPeriodSl liao = new ProductGzPeriodSl();
                for (ProductGzPeriodSl sl : gzPeriodSlList) {
                    String endTime = sl.getEndTime();
                    if (StringUtils.isEmpty(endTime)) {
                        if (StringUtils.equals(sl.getSlType(), "1")) {
                            shui = sl;
                        } else {
                            liao = sl;
                        }
                    }
                }
                if (StringUtils.isEmpty(shui.getId())) {
                    if (StringUtils.isNotEmpty(waterStartTime)) {
                        ProductGzPeriodSl newSl = new ProductGzPeriodSl();
                        newSl.setId(CommonUtil.generateRandomNum("sl-"));
                        newSl.setSlType("1");
                        newSl.setGzId(period.getId());
                        newSl.setStartTime(waterStartTime);
                        if (StringUtils.isNotEmpty(firstWaterEndTime) && firstWaterEndTime.compareTo(waterStartTime) > 0) {
                            long timestamp = simpleDateFormat.parse(firstWaterEndTime).getTime() - simpleDateFormat.parse(waterStartTime).getTime();
                            double min = (timestamp / 1000.0) / 60.0;
                            newSl.setSlValue(NumberUtil.getPoint(min, 1));
                        }
                        gzPeriodSls.add(newSl);
                    }
                } else {
                    if (StringUtils.isNotEmpty(firstWaterEndTime)) {
                        shui.setEndTime(firstWaterEndTime);
                        long timestamp = simpleDateFormat.parse(shui.getStartTime()).getTime() - simpleDateFormat.parse(waterStartTime).getTime();
                        double min = (timestamp / 1000.0) / 60.0;
                        shui.setSlValue(NumberUtil.getPoint(min, 1));
                        gzUpdatePeriodSls.add(shui);
                    }
                }
                if (StringUtils.isEmpty(liao.getId())) {
                    if (StringUtils.isNotEmpty(liaoStartTime)) {
                        ProductGzPeriodSl newSl = new ProductGzPeriodSl();
                        newSl.setId(CommonUtil.generateRandomNum("sl-"));
                        newSl.setSlType("2");
                        newSl.setGzId(period.getId());
                        newSl.setStartTime(liaoStartTime);
                        if (StringUtils.isNotEmpty(firstliaoEndTime) && firstliaoEndTime.compareTo(liaoStartTime) > 0) {
                            long timestamp = simpleDateFormat.parse(firstliaoEndTime).getTime() - simpleDateFormat.parse(liaoStartTime).getTime();
                            double min = (timestamp / 1000.0) / 60.0;
                            newSl.setSlValue(NumberUtil.getPoint(min, 1));
                        }
                        gzPeriodSls.add(newSl);
                    }
                } else {
                    if (StringUtils.isNotEmpty(firstliaoEndTime)) {
                        liao.setEndTime(firstliaoEndTime);
                        long timestamp = simpleDateFormat.parse(liao.getEndTime()).getTime() - simpleDateFormat.parse(liao.getStartTime()).getTime();
                        double min = (timestamp / 1000.0) / 60.0;
                        liao.setSlValue(NumberUtil.getPoint(min, 1));
                        gzUpdatePeriodSls.add(liao);
                    }
                }

            }

        }
    }

    private void getShaojieNeedUpdateDatas(List<ProductSaojieJob> needUpdateJobs, Map<String, List<ProductSaojieJob>> saojieJobMap, String room, List<ProductSaojieGuan> productSaojieGuans, String factoryName) throws Exception {
        for (int i = 1; i <= 12; i++) {
            double up = i / 2.0;
            int line = (int) Math.ceil(up);
            int code = i % 2 == 0 ? 2 : 1;
            String key = room + "-" + line + "" + code;
            List<String> redis = Lists.newArrayList();
            long roomSize = redisTemplate.opsForList().size(key);
//            List<String> redis = redisTemplate.opsForList().range(key, 0, roomSize);
            for (int m = 0; m < roomSize; m++) {
                Object value = redisTemplate.opsForList().rightPop(key);
                if (null != value) {
                    redis.add(value.toString());
                }
            }

            if (CollectionsUtil.isEmpty(redis)) {
                continue;
            }
            List<JSONObject> redisJsons = Lists.newLinkedList();
            for (int j = 0; j < redis.size(); ++j) {
                try {
                    System.out.println("==================saojie===============");
                    System.out.println(redis.get(j));
                    JSONObject roomObject = JSON.parseObject(redis.get(j));
                    redisJsons.add(roomObject);
                } catch (Exception e) {

                }
            }

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Collections.sort(redisJsons, new Comparator<JSONObject>() {
                @Override
                public int compare(JSONObject o1, JSONObject o2) {
                    String timeStamp1 = o1.getString("TimeStamp");
                    String timeStamp2 = o2.getString("TimeStamp");
                    if (StringUtils.isEmpty(timeStamp1)) {
                        return 1;
                    } else if (StringUtils.isEmpty(timeStamp2)) {
                        return -1;
                    }
                    long timeStampLong1 = 0;
                    long timeStampLong2 = 0;
                    try {
                        timeStampLong1 = (simpleDateFormat.parse(timeStamp1).getTime()) / 1000;
                        timeStampLong2 = (simpleDateFormat.parse(timeStamp2).getTime()) / 1000;
                    } catch (Exception e) {

                    }
                    //从小到大排序
                    return (int) (timeStampLong1 - timeStampLong2);
                }
            });

            ProductSaojieGuan guan = new ProductSaojieGuan();
            guan.setFactoryName(factoryName);
            String lasterStart = redisJsons.get(redisJsons.size() - 1).getString("Start");
            if (StringUtils.equals(lasterStart, "True")) {
                guan.setGuanStatus("1");
            } else {
                guan.setGuanStatus("2");
            }
            guan.setSaojieGuan(i + "");
            productSaojieGuans.add(guan);
            if (!saojieJobMap.containsKey(key)) {
                continue;
            }


            List<ProductSaojieJob> saojieJobs = saojieJobMap.get(key);
            String firstGoodTime = "";
            List<Integer> badIndex = Lists.newLinkedList();
            for (int j = 0; j < redisJsons.size(); ++j) {
                String Start = redisJsons.get(j).getString("Start");
                if (StringUtils.equals(Start, "True") && StringUtils.isEmpty(firstGoodTime)) {
                    firstGoodTime = redisJsons.get(j).getString("TimeStamp");
                }
                if (StringUtils.equals(Start, "False")) {
                    if (badIndex.size() == 0) {
                        badIndex.add(j);
                    } else {
                        String pre = redisJsons.get(j - 1).getString("Start");
                        if (StringUtils.equals(pre, "True")) {
                            badIndex.add(j);
                        }
                    }
                }
            }
            JSONObject lastest = redisJsons.get(redisJsons.size() - 1);
            for (ProductSaojieJob saojieJob : saojieJobs) {
                saojieJob.setValue1(lastest.getString("Looptime"));
                saojieJob.setValue2(lastest.getString("Speed"));
                saojieJob.setValue3(lastest.getString("PrNo1"));
                saojieJob.setValue4(lastest.getString("Danliuliang"));
                saojieJob.setValue17(lastest.getString("Cycle"));
                if (StringUtils.isEmpty(saojieJob.getValue6())) {
                    saojieJob.setValue6(lastest.getString("TimeStamp"));
                }
                String value5 = "";
                for (int m = 1; m <= 29; m++) {
                    String mkey = m < 10 ? ("0" + i) : m + "";
                    String downKey = "S" + mkey + "L_PV";
                    String upKey = "S" + mkey + "U_PV";
                    String downTemp = lastest.getString(downKey);
                    String upTemp = lastest.getString(upKey);
                    if (StringUtils.isEmpty(downTemp)) {
                        downTemp = "";
                    }
                    if (StringUtils.isEmpty(upTemp)) {
                        upTemp = "";
                    }
                    String tempQuJian = downTemp + "-" + upTemp;
                    value5 += tempQuJian + ",";
                }
                int errorCount = 0;
                saojieJob.setValue5(value5);
//                String lastetBadDownTime = "";
                String lastetBadUpTime = "";
                if (StringUtils.isNotEmpty(saojieJob.getValue9())) {
                    ++errorCount;
                    String splits[] = saojieJob.getValue9().split("-");
//                    lastetBadDownTime = saojieJob.getValue9().split("-")[0];
                    if (splits.length == 2 && StringUtils.isEmpty(splits[1])
                            && StringUtils.isNotEmpty(firstGoodTime)) {
                        lastetBadUpTime = splits[1];
                        saojieJob.setValue9(saojieJob.getValue9() + firstGoodTime);
                    }
                }

                if (StringUtils.isNotEmpty(saojieJob.getValue10())) {
                    ++errorCount;
                    String splits[] = saojieJob.getValue10().split("-");
//                    lastetBadDownTime = saojieJob.getValue10().split("-")[0];
                    if (splits.length == 2 && StringUtils.isEmpty(splits[1])
                            && StringUtils.isNotEmpty(firstGoodTime)) {
                        lastetBadUpTime = splits[1];
                        saojieJob.setValue10(saojieJob.getValue10() + firstGoodTime);
                    }
                }
                if (StringUtils.isNotEmpty(saojieJob.getValue11())) {
                    ++errorCount;
                    String splits[] = saojieJob.getValue11().split("-");
//                    lastetBadDownTime = saojieJob.getValue11().split("-")[0];
                    if (splits.length == 2 && StringUtils.isEmpty(splits[1])
                            && StringUtils.isNotEmpty(firstGoodTime)) {
                        lastetBadUpTime = splits[1];
                        saojieJob.setValue11(saojieJob.getValue11() + firstGoodTime);
                    }
                }
                if (badIndex.size() > 0) {
                    for (int index = 0; index < badIndex.size(); index++) {
                        int redisIndex = badIndex.get(index);
                        String time = redisJsons.get(redisIndex).getString("TimeStamp");
                        if ((StringUtils.isNotEmpty(lastetBadUpTime) && time.compareTo(lastetBadUpTime) > 0)
                                || (StringUtils.isNotEmpty(firstGoodTime) && time.compareTo(firstGoodTime) > 0)) {
                            String badArea = "";
                            if (index == badIndex.size() - 1) {
                                badArea = time + "-";
                            } else {
                                int redisNextIndex = badIndex.get(index + 1) - 1;
                                String netxTime = redisJsons.get(redisNextIndex).getString("TimeStamp");
                                badArea = time + "-" + netxTime;
                            }
                            if (StringUtils.isEmpty(saojieJob.getValue9())) {
                                saojieJob.setValue9(badArea);
                                ++errorCount;
                            } else if (StringUtils.isEmpty(saojieJob.getValue10())) {
                                saojieJob.setValue10(badArea);
                                ++errorCount;
                            } else if (StringUtils.isEmpty(saojieJob.getValue11())) {
                                saojieJob.setValue11(badArea);
                                ++errorCount;
                            }
                        }
                    }
                }
                long stopSecond = 0;
                String guanStatus = "1";
                if (StringUtils.isNotEmpty(saojieJob.getValue9())) {
                    String splits[] = saojieJob.getValue9().split("-");
                    if (splits.length == 2 && StringUtils.isNotEmpty(splits[1])) {
                        Date start = simpleDateFormat.parse(splits[0]);
                        Date end = simpleDateFormat.parse(splits[1]);
                        stopSecond += (end.getTime() - start.getTime()) / 1000;
                    } else {
                        guanStatus = "2";
                    }
                }

                if (StringUtils.isNotEmpty(saojieJob.getValue10())) {
                    String splits[] = saojieJob.getValue10().split("-");
                    if (splits.length == 2 && StringUtils.isNotEmpty(splits[1])) {
                        Date start = simpleDateFormat.parse(splits[0]);
                        Date end = simpleDateFormat.parse(splits[1]);
                        stopSecond += (end.getTime() - start.getTime()) / 1000;
                    } else {
                        guanStatus = "2";
                    }
                }
                if (StringUtils.isNotEmpty(saojieJob.getValue11())) {
                    String splits[] = saojieJob.getValue11().split("-");
                    if (splits.length == 2 && StringUtils.isNotEmpty(splits[1])) {
                        Date start = simpleDateFormat.parse(splits[0]);
                        Date end = simpleDateFormat.parse(splits[1]);
                        stopSecond += (end.getTime() - start.getTime()) / 1000;
                    } else {
                        guanStatus = "2";
                    }
                }
                double min = stopSecond / 60.0;
                saojieJob.setValue7(errorCount + "");
                saojieJob.setValue8(NumberUtil.getPoint(min, 1));
                saojieJob.setYaoGuanStatus(guanStatus);
                needUpdateJobs.add(saojieJob);

            }

        }
    }


    public static void main(String args[]) throws Exception {

        String mstart = "2025-01-13T11:39:32.1148193+08:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long startTimeStamp = simpleDateFormat.parse(mstart).getTime();
        String startTime = simpleDateFormat1.format(new Date(startTimeStamp));
        System.out.println(startTime);
    }

}
